import argparse
import asyncio
import logging

from concurrent.futures import CancelledError

from BitClient.torrent import Torrent
from BitClient.client import TorrentClient

from threading import Thread

def main():
    # parser = argparse.ArgumentParser()
    # parser.add_argument('torrent',
    #                     help='the .torrent to download')
    # parser.add_argument('-v', '--verbose', action='store_true',
    #                     help='enable verbose output')

    # args = parser.parse_args()
    # if args.verbose:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(pathname)s %(lineno)s %(funcName)s %(levelname)s - %(message)s") #%(filename)s 

    # logging.debug('hello')

    # exit()

    import multiprocessing
 
    def downloader_backend() -> None:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        torrent = Torrent('./tests/debian-12.1.0-amd64-netinst.iso.torrent')
        logging.info("Read torrent with info: \n{}".format(torrent))
        client = TorrentClient(torrent)
        task = loop.create_task(client.start())

        try:
            loop.run_until_complete(task)
        except CancelledError:
            logging.warning('Event loop was canceled')

        return 

    # downloader_process = multiprocessing.Process(target=downloader_backend)
    # downloader_process.start()

    # print("ID of process p1: {}".format(downloader_process.pid)) 

    from gui import GuiPiece
    import os
    from hashlib import sha1

    torrent = Torrent('./tests/debian-12.1.0-amd64-netinst.iso.torrent')
    # fd = os.open('/home/omnisky/APP/myBitClient/debian-12.1.0-amd64-netinst.iso', os.O_RDONLY)

    # def simple_gui():
    #     while True:
    #         have_pieces = []
    #         missing_pieces = []

    #         for index, piece in enumerate(torrent.pieces):
    #             piece_in = os.read(fd, torrent.piece_length)

    #             if sha1(piece_in).digest() == piece:
    #                 # print('ok')
    #                 have_pieces.append(piece)
    #                 # gui_piece[index].select()
    #                 guipiece.update_piece(index, 2)
    #             else:
    #                 missing_pieces.append(piece)
    #         print(len(have_pieces))
    #         sleep(5)

    class guiThread(Thread):
        def __init__(self, name) -> None:
            super().__init__()
            self.name = name

        def run(self) -> None:
            guipiece = GuiPiece(len(torrent.pieces))
            guipiece.top.mainloop()
            return super().run()



    # simple_gu_process = multiprocessing.Process(target=simple_gui)
    # simple_gu_process.start()

    gui_threaad = guiThread('gui')
    gui_threaad.start()

    downloader_backend()

    # tt = Torrent('./tests/debian-12.1.0-amd64-netinst.iso.torrent')
    # from BitClient.tracker import Tracker
    # tk = Tracker(tt)
    # loop.run_until_complete(tk.connect())
    # loop.close()

    
    # torrent = Torrent('/home/omnisky/Desktop/SHARE/[DKB] Synduality Noir - S01E07 [1080p][HEVC x265 10bit][Multi-Subs].mkv.torrent')
    

    

    # def signal_handler(*_):
    #     logging.info('Exiting, please wait until everything is shutdown...')
    #     client.stop()
    #     task.cancel()

    # signal.signal(signal.SIGINT, signal_handler)

    

if __name__ == '__main__':
    main()